package com.tuanzi.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tuanzi.blog.NotFoundException;
import com.tuanzi.blog.dao.TypeMapper;
import com.tuanzi.blog.model.Type;
import com.tuanzi.blog.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 雄关漫道真如铁，而今迈过从头越
 **/

@Service
public class TypeServiceImpl implements TypeService {

    @Resource
    private TypeMapper typeMapper;


    /**
     * 查询所有类型信息
     */
    @Transactional
    @Override
    public List<Type> getAllTypes() {

        List<Type> types = typeMapper.selectAllTypeInfo();

        return types;
    }


    /**
     * 1.插入成功
     * 2.插入失败
     * 3.数据库中已经有了
     */
    @Transactional
    @Override
    public int saveType(Type type) {
        if (typeMapper.selectByName(type.getName()) == null){
            if (typeMapper.insert(type) == 1){
                return 1;
            }
            return 2;
        }
        return 3;
    }

    @Transactional
    @Override
    public Type getType(Long id) {
        return typeMapper.selectByPrimaryKey(id);
    }


    /**
     * 1.更新成功
     * 2.更新失败
     * 3.数据库中已经有了
     */
    @Transactional
    @Override
    public int updateType(Long id, Type type) {
        Type t = typeMapper.selectByPrimaryKey(id);
        if (t == null){
            throw new NotFoundException("不存在该类型");
        }
        if (t.getName().equals(type.getName())){
            return 3;
        }
        BeanUtils.copyProperties(type,t);
        if (typeMapper.updateByPrimaryKey(type) != 0){
            return 1;
        }
        return 2;
    }

    @Transactional
    @Override
    public Type deleteType(Long id) {
        Type type = typeMapper.selectByPrimaryKey(id);
        int i = typeMapper.deleteByPrimaryKey(id);
        if (i == 1){
            return type;
        }else{
            return null;
        }
    }

}
